package com.ruoyi.web.controller.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.webresources.FileResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
@Slf4j
public class CommonController {
//    private static final Logger log = LoggerFactory.getLogger(CommonController.class);
    private String url1 ="http://wubu.xzrenli.com";
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.checkAllowDownload(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
//            String filePath="/usr/local/cret";
            System.out.println("路径"+filePath);
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            System.out.println(serverConfig.getUrl());
            System.out.println(fileName);
            String url = url1 + fileName;
//            String url = serverConfig.getUrl() + fileName;
            System.out.println(url);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * @param files 批量上传的文件
     * @return 上传成功条数
     */
    @PostMapping("/uploadfilePIC")
    public AjaxResult uploadByPIC(@RequestParam("file") MultipartFile[] files) {
        int count1 = -1;
        int count2 = -1;
        String url="";
        try {
            for (MultipartFile file : files) {
                long size = file.getSize();
                if (!FileUploadUtils.getExtension(file).equals("png") && !FileUploadUtils.getExtension(file).equals("jpg")
                        && !FileUploadUtils.getExtension(file).equals("JPG") &&
                        !FileUploadUtils.getExtension(file).equals("PNG") && !FileUploadUtils.getExtension(file).equals("jpeg")
                        && !FileUploadUtils.getExtension(file).equals("JPEG")
                        && !FileUploadUtils.getExtension(file).equals("gif")
                        && !FileUploadUtils.getExtension(file).equals("GIF")) {
                    return AjaxResult.error("文件格式错误请上传png/jpg/jpeg/gif格式文件！");
                }
                int fileNamelength = file.getOriginalFilename().length();
                if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
                    return AjaxResult.error("文件名字过长");
                }
                if ((FileUploadUtils.DEFAULT_MAX_SIZE * 1024 * 1024) != -1 &&
                        size > (FileUploadUtils.DEFAULT_MAX_SIZE * 1024 * 1024)) {
                    return AjaxResult.error("文件过大，请重新上传");
                }
                //重新写一个编码格式，将工单号拼到图片名中
                String fileName = FileUploadUtils.extractFilename(file);
                log.info("头像"+fileName);
// url=url+serverConfig.getUrl() + Constants.RESOURCE_PREFIX + "/" +fileName;
                url=url+ url1 +fileName;
                File desc = new File(FileUploadUtils.getDefaultBaseDir() + File.separator + fileName);
                if (!desc.getParentFile().exists()) {
                    desc.getParentFile().mkdirs();
                }
                if (!desc.exists()) {
                    desc.createNewFile();
                }
                file.transferTo(desc);
            }
            log.info(url+"==============");
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        return AjaxResult.success("上传完成");
    }


    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
